﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Services.Client;
using TestDS.MySvc;
using System.Net;
using System.IO;
using System.Xml;

namespace TestDS
{
	class Program
	{
		static void Main(string[] args)
		{
			string url = "http://localhost:1206/WcfDataService.svc";
			Uri u = new Uri(url);
			//Generic
			{
				DataServiceContext ctx = new DataServiceContext(u);
				var q = ctx.Execute<Order>(new Uri("/Orders(10402)", UriKind.Relative));
				foreach (var t in q)
				{
					Console.WriteLine(t.OrderDate);
				}
			}

			//Client Proxy
			{
				NorthwindEntities ctx = new NorthwindEntities(u);
				var q = from c in ctx.Suppliers select c;
				foreach (var t in q)
				{
					Console.WriteLine(t.City);
				}

				///添加
				var cust = new Customer()
				{
					CustomerID = "Test1",
					Address = "Beijing",
					City = "Peking",
					CompanyName = "demo",
					ContactName = "test",
					ContactTitle = "mr.",
					Country = "China",
					Fax = "123",
					Phone = "111",
					PostalCode = "456",
					Region = "HD"
				};

				ctx.AddToCustomers(cust);
				ctx.SaveChanges();

				///更新
				var upCust = (from c in ctx.Customers where c.CustomerID == cust.CustomerID select c).FirstOrDefault();
				upCust.ContactName += "-UPD";
				ctx.UpdateObject(upCust);
				ctx.SaveChanges();

				///删除
				upCust = (from c in ctx.Customers where c.CustomerID == cust.CustomerID select c).FirstOrDefault();
				ctx.DeleteObject(upCust);
				ctx.SaveChanges();
			}

			//HTTP 
			{
				HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url + "/Orders(10402)");
				req.Method = "GET";
				req.Accept = "application/json";
				using (HttpWebResponse resp = (HttpWebResponse)req.GetResponse())
				{
					using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
					{
						Console.WriteLine(sr.ReadToEnd());
					}
				}

				req = (HttpWebRequest)WebRequest.Create(url + "/Orders(10402)");
				req.Method = "GET";
				req.Accept = "application/atom+xml";
				using (HttpWebResponse resp = (HttpWebResponse)req.GetResponse())
				{
					using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
					{
						XmlDocument xml = new XmlDocument();
						xml.Load(sr);

						Console.WriteLine(xml.InnerXml);
					}
				}
			}
		}
	}
}
